package com.yuven.appframework.widget

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.core.view.forEachIndexed
import com.yuven.appframework.R


class IndicatorLayout @JvmOverloads constructor( context: Context, attrs:AttributeSet? = null):LinearLayout(context, attrs) {
    private  var defaultIcon = 0
    private  var selectedIcon = 0
    private  var count = 0
    private var position =0

    init {
       val typeArray =  context.obtainStyledAttributes(attrs, R.styleable.indicator)
        defaultIcon =  typeArray.getResourceId(R.styleable.indicator_defaultIcon,0)
        selectedIcon =  typeArray.getResourceId(R.styleable.indicator_selectedIcon,0)
        count =  typeArray.getInt(R.styleable.indicator_num,0)
        typeArray.recycle()
        initView()

    }

    fun initView(){
        for (i in 0..count){
            val imageView = ImageView(context)
            addView(imageView)
        }
        refreshView()
    }

    fun setCurrentPosition(position:Int){
        this.position = position
        refreshView()
    }

    private fun refreshView(){
        forEachIndexed { index, view ->
            view as ImageView
            if (index == position){
                view.setBackgroundResource(selectedIcon)
            }else{
                view.setBackgroundResource(defaultIcon)
            }
        }
    }
}